<?php
namespace control;
/*
*采购申请单类
*/

class purchaseApplyClass extends adIndexClass
{
    private const page = 'purchaseApply';
    private const table = 'purchase_apply';
    private const tableMx = 'purchase_apply_detail';
    private const title = '采购申请';
    private const stateOption = ['草稿', '审核中', '已通过'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '单据编号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'type' => [
                        'name'  => "请购类型",
                        'width' => 270,
                    ],
                    'num'  => [
                        'name'  => "数量",
                        'width' => 150,
                    ],
//                    'purchase_num'         => [
//                        'name'  => '采购数量',
//                        'width' => 150,
//                    ],
//                    'receive_num'          => [
//                        'name'  => '收货数量',
//                        'width' => 150,
//                    ],
                    'demandDate'          => [
                        'name'  => '需求日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'recordDate'          => [
                        'name'  => '单据日期',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 200,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "请购类型"   => select(["name" => "type", 'option' => explode('，', para('purchaseType'))]),
                    '单据日期' => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
                [
                    "状态" => select(["name" => "state", 'option' => self::stateOption]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $isEdit = $this->power(self::page, "edit");
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($isEdit) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "close")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'close'})\">批量关闭</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            "state" => $this->post('state'),
            "type" => $this->post('type'),
            "coid" => self::$coid,
        );
        $and = '';
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'recordDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate desc,time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        $isEdit = $this->power(self::page, "edit");
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
                'track'=> array("title" => "单据追踪", "click" => "newIframe('单据追踪','" . root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=采购申请单&id=" . $array['id'] . "')"),
            );
            if ($array['state'] != '草稿' || !$isEdit) {
                unset($dominate['edit']);
            }
            if ($array['isClose'] == 1) {
                $array['state'] = '已完成';
            }
            $closeSign = $array['isClose'] ? "<span class='no-choose'></span>" : '';//关闭单据颜色显示标志
            $liButton[] = $this->dominate($dominate) . $closeSign;
            $total = find(array('table' => self::tableMx, 'single' => "orderId = '$array[id]'", 'field' => " IFNULL(sum(num),0) as num,IFNULL(sum(purchase_num),0) as purchase_num,IFNULL(sum(receive_num),0) as receive_num "));
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "num":
                        $row[] = self::lostZero($total['num'],'numPrecision');
                        break;
                    case "purchase_num":
                        $row[] = self::lostZero($total['purchase_num'],'numPrecision');
                        break;
                    case "receive_num":
                        $row[] = self::lostZero($total['receive_num'],'numPrecision');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::tableMx,
            'single' => "orderId in (select id from ".self::table." where 1=1 {$where})",
            'field'  => "ifnull(sum(num),0) as num,ifnull(sum(purchase_num),0) as purchase_num,ifnull(sum(receive_num),0) as receive_num",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
            'purchase_num'   => self::lostZero($totalQuery['purchase_num'], 'numPrecision'),
            'receive_num' => self::lostZero($totalQuery['receive_num'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>". machiningOrderClass::closeJs() . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 单据追踪
     * @return string
     */
    public function track(): string
    {
        $orderTrackClass = new orderTrackClass();
        return $orderTrackClass->home();
    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id')?:suiji();
        $info = query(self::table, " id = '" . $id . "' ");

        $button[] = [
            "name" => "保存",
            "type" => "点击事件",
            "title" => "保存",
            'fun' => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')"
        ];
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name" => '保存并提交',
            "type" => "弹出层",
            "cla" => $this->get('cla'),
            "fun" => "saveAndCommit",
            "post" => "$('[name=" . self::page . "EditForm]').serialize()+'&act=start'",
        ];
        $tr[] = ['', '物料编码', '物料名称', '规格型号', '单位', '数量', '可用库存','图片', '备注'];
        $totalArr = ['total_num'=>0,'inventory'=>0];

        $title = self::title;
        $power = root . "control/adIndex.html?cla={$this->get('cla')}&fun=uploadIco";

        if ($this->get('source') == 'materialDemand') {
            //材料需求
            $id = self::getId();
            $listId = $this->get('listId');
            $result = purchaseOrderClass::mergeMaterial($listId);//合并相同的物料
            $list = 0;
            foreach ($result as $array) {
                $material = query('material', " id = '$array[materialId]'");
                $num = machiningOrderClass::material_num_change($material['id'], $array['unit'], $material['unit'], $array['num']);
                $inventoryNum = machiningOrderClass::inventory($array['materialId'],$material['unit']);
                $tr[] = [
                    componentClass::tablePperation($list+1,"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => self::getId())) .
                    hidden(array('name' => 'materialId[]', 'value' => $array['materialId'])) ,
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    select(array('name' => 'unit[]', 'data' => ['unit' => $material['unit']], 'change' => 'unitChange', 'option' => machiningOrderClass::unitOption($material['id']), 'title' => '单位', 'value' => $material['unit'])),
                    text(array('name' => 'num[]', 'blur' => 'calculateTotal', 'other' => self::digitalFiltering('numPrecision'),  'value' => self::lostZero($num,'numPrecision'))),
                    "<span class='inventoryNum'>" . $inventoryNum . "</span>",
                    "",
                    text(array('name' => 'mxText[]', 'class' => 'text textPrice', 'value' => '')),
                ];
                $totalArr['total_num'] += $num;
                $totalArr['inventory'] += $inventoryNum;
                $list++;
            }
        }elseif($this->get('source') == 'purchaseDemand'){
            //外购需求
            $id = self::getId();
            $listId = $this->get('listId');
            $result = self::mergeMaterial($listId);//合并相同的物料
            $list = 0;
            foreach ($result as $array) {
                $material = query('material', " id = '$array[materialId]'");
                $num = machiningOrderClass::material_num_change($material['id'], $array['unit'], $material['unit'], $array['num']);
                $inventoryNum = machiningOrderClass::inventory($array['materialId'],$material['unit']);
                $tr[] = [
                    componentClass::tablePperation($list+1,"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => self::getId())) .
                    hidden(array('name' => 'materialId[]', 'value' => $array['materialId'])) ,
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    select(array('name' => 'unit[]', 'data' => ['unit' => $material['unit']], 'change' => 'unitChange', 'option' => machiningOrderClass::unitOption($material['id']), 'title' => '单位', 'value' => $material['unit'])),
                    text(array('name' => 'num[]', 'blur' => 'calculateTotal', 'other' => self::digitalFiltering('numPrecision'),  'value' => self::lostZero($num,'numPrecision'))),
                    "<span class='inventoryNum'>" . $inventoryNum . "</span>",
                    "",
                    text(array('name' => 'mxText[]', 'class' => 'text textPrice', 'value' => '')),
                ];
                $totalArr['total_num'] += $num;
                $totalArr['inventory'] += $inventoryNum;
                $list++;
            }
        } else {
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            foreach ($result['array'] as $k=>$array) {
                $material = query('material', " id = '$array[materialId]'");
                $inventoryNum = machiningOrderClass::inventory($array['materialId'],$material['unit']);
                $fileData = query("file","targetId = '{$array['id']}' and target='{$title}'");
                $imageUrl = '';
                $imagetitle = '';
                if($fileData['id']){
                    $imageUrl = root.$fileData['src'];
                    $imagetitle = $fileData['name'];
                }
                $tr[] = [
                    componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $array['id'])) .
                    hidden(array('name' => 'materialId[]', 'value' => $array['materialId'])),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    select(array('name' => 'unit[]', 'data' => ['unit' => $array['unit']], 'change' => 'unitChange', 'option' => machiningOrderClass::unitOption($material['id']), 'title' => '单位', 'value' => $array['unit'])),
                    text(array('name' => 'num[]', 'blur' => 'calculateTotal', 'other' => self::digitalFiltering('numPrecision'), 'value' => self::lostZero($array['num'],'numPrecision'))),
                    "<span class='inventoryNum'>" . $inventoryNum . "</span>",
                "<div class='clickIco' title='上传'><img  src='" . root . "img/control/clickEdit.svg?v=".version."' onClick=\"clickUpload('{$title}')\" class='edit-ico'>".
                "<a target='_blank' id='{$array['id']}Look' href='" . $imageUrl . "?time=" . time() . "'><img alt='' src='" . root . "img/control/img.svg' title='" . $imagetitle . "' class='listIco'></a>".
                "<a target='_blank' id='{$array['id']}dow' href='" . $imageUrl . "' download='" . $material['name'] . "' title='" . $imagetitle . "'><img  alt='' src='" . root . "img/control/download.svg' class='listIco'></a></div>".
                    "<div class='hidden'><input name=\"singleFrameImgType\" type=\"hidden\"><input name=\"imageId[]\" id='{$array['id']}' type=\"hidden\" value='{$imageUrl}'><input name='imgFile' accept=\"image/*\" id='imgFile' type='file' onchange=\"uploadImgFile(this,'{$power}','{$array['id']}')\"></div>",
                    text(array('name' => 'mxText[]', 'class' => 'text textPrice', 'value' => $array['text'])),
                ];
                $totalArr['total_num'] += $array['num'];
                $totalArr['inventory'] += $inventoryNum;
            }
        }
        $total = [
            5 => "<span id='total_num'>".self::lostZero($totalArr['total_num'],'numPrecision')."</span>",
            6 => "<span id='total_inventory'>".self::lostZero($totalArr['inventory'],'numPrecision')."</span>",
        ];
        $list = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total));
        $mxButton = <<<efo
              <span class="smallButton" onclick="layer('{$this->get('cla')}','addMx',$('form[name=purchaseApplyEditForm]').serialize())">选择物料</span>
efo;

        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . "请购类型：" => select(["name" => "type", 'title' => '请选择', 'option' => explode('，', para('purchaseType')), "value" => $info['type']]),
                    must . "单据日期：" => text(["name" => "recordDate", 'class' => 'text', 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                    must . "需求日期：" => text(["name" => "demandDate", 'class' => 'text', 'laydate' => [], "value" => $info['demandDate']]),
                ],
                [
                    "备注：" => textarea(["name" => "text", 'class' => 'text', "value" => $info['text']]),
                    "类型：" => radio(["name" => "goods_type", 'value' => ['大宗物资', '小宗物资'], "checked" => $info['goods_type'] ?: '小宗物资']),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => '请购明细',
            'button' => $mxButton,
            'html' => $list,
        ]);
        $body .= $this->editBlock([
            '附件' => fileUploadClass::addFileComponent($id, self::title, self::page, self::page . 'EditForm')
        ]);
        $data['html'] = $this->pageEdit([
            "html" => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $data['html'] .= <<<efo
<script>
function addRow(){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
        $('#purchaseApplyAddMx').hide();
        $("#materialTable tbody").append(res.html);
        resetNumber($("#materialTable"))
        calculateTotal()
    },'json');
}

//点击上传图片
function clickUpload(type){
    $('[name=singleFrameImgType]').val(type);
    $('#imgFile').click();
}

function getLookImg(type,id) {
  
}

        //上传图片
        function uploadImgFile(that,url,id){
            let type= $('[name=singleFrameImgType]').val();
            var formData = new FormData();
            formData.append("imgFile", that.files[0]);// 获取第一个上传的文件对象
            formData.append("type", type); 
            formData.append("id", id); 
            $.ajax({
                type: "POST",
                contentType: false,
                processData: false,
                url: url,
                data: formData,
                cache: false,
                success: function (res) {
                    let result = JSON.parse(res);
                    $("[name='imgFile']").val('');
                    if (result.warn === 2) {
                        $("#"+id).val(result.data.src);
                        $("#"+id+"Look").attr('href',result.data.src);
                        $("#"+id+"dow").attr('href',result.data.src);
                    }else{
                        warn(result.warn)
                    }
                },
                error: function (e) {
                    console.log(e)
                    warn("上传失败");
                }
            });
        }

//根据单位转换所需数量和库存
function unitChange(e){
    let unit = e.value;
    if (!unit){
        msg('请选择单位')
        return '';
    }
    let oldUnit = $(e).data('unit');
    $(e).data('unit',unit);
    let num = $(e).parent().parent().find("[name='num[]']").val();
    let id = $(e).parent().parent().find("[name='materialId[]']").val();
    $.post(root+'control/adIndex.html?cla=machiningInOrder&fun=unitChange',{unit:unit,oldUnit:oldUnit,num:num,id:id},function(res) {
        if (res.warn==2){
            $(e).parent().parent().find("[name='num[]']").val(res.num);
            $(e).parent().parent().find(".inventory").html(res.inventoryNum);
        }else{
            msg(res.warn);
        }
    },'json');
}
//计算总数量
function calculateTotal(){
    let table = $('.editList')
    let num = 0,
    inventoryNum = 0
    table.find("[name='num[]']").each(function(index){
        if($(this).val()){
          num+=Number($(this).val());
        }
        var inventoryNumText = table.find(".inventoryNum").eq(index).text()
        if(inventoryNumText){
            inventoryNum+=Number(inventoryNumText);
        }
    })
    $("#total_num").text(num.toFixed(publicSettings.numPrecision.num));
    $("#total_inventory").text(inventoryNum.toFixed(publicSettings.numPrecision.num));
}
</script>

efo;
        //返回
        return $this->tab($data);
    }

    /**
     *上传个人资料
     */
    function uploadIco(): bool|string
    {
        $type = $this->post('type');
        $info = query(self::tableMx, " id = '{$this->post('id')}'");
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } else {
            $talentPool = new talentPoolClass();
            return $talentPool->saveIco(self::page, $info['id'], $type, $_FILES);
        }
        return json_encode($json, 320);
    }

    /**
     * 合并采购需求
     * @param $listId
     * @return array
     */
    public static function mergeMaterial($listId): array
    {
        $result = [];
        if (empty($listId)){
            return  $result;
        }else{
            $listArr = explode(',',$listId);
            foreach ($listArr as $id){
                $purchase_demands = query('purchase_demands',"id = '$id'");
                $material = query('material',"id = '$purchase_demands[materialId]'");
                $supplyControl = explode(',',$material['supplyControl']);
                if(in_array('允许采购',(array)$supplyControl)) {
                    if (!array_key_exists($purchase_demands['materialId'], $result)) {
                        $result[$purchase_demands['materialId']] = [
                            'num' => machiningOrderClass::material_num_change($purchase_demands['materialId'], $purchase_demands['unit'], $material['unit'], $purchase_demands['num']),
                            'unit' => $material['unit'],
                            'materialId' => $purchase_demands['materialId'],
                        ];
                    } else {
                        $result[$purchase_demands['materialId']]['num'] = $result[$purchase_demands['materialId']]['num'] + machiningOrderClass::material_num_change($purchase_demands['materialId'], $purchase_demands['unit'], $result[$purchase_demands['materialId']]['unit'], $purchase_demands['num']);
                    }
                }
            }
        }
        return $result;
    }

    public function editEdit()
    {
        $fileIdArr = $this->post('fileId');
        $id = $this->post('id') ?: self::getId();
        $mxIdArr = $this->post('mxId') ?: [];
        $materialIdArr = $this->post('materialId');
        $numArr = $this->post('num');
        $mxTextArr = $this->post('mxText');
        $unitArr = $this->post('unit');
        $field = [
            'type' => $this->post('type'),
            'goods_type' => $this->post('goods_type'),
            'text' => $this->post('text'),
            'recordDate' => $this->post('recordDate'),
            'demandDate' => $this->post('demandDate'),
        ];
        $annotation = [
            'type' => '请购类型',
            'recordDate' => '单据日期',
        ];
        $rules = [
            'type' => 'required',
            'recordDate' => 'required|date',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::is_null_array($mxIdArr)) {
            $json['warn'] = '请选择请购明细';
        } elseif (static::is_null_array($materialIdArr)) {
            $json['warn'] = '请选择请购明细';
        } elseif (static::is_null_array($numArr)) {
            $json['warn'] = '数量请填写完整';
        }  elseif (static::is_null_array($unitArr)) {
            $json['warn'] = '单位请选择完整';
        } elseif (!empty($info['id']) && $info['state'] == '已确认') {
            $json['warn'] = '此采购申请单已确认，不能修改';
        } else {
            $this->startTrans();
            $isPass = true;//事务通过标志
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'CGSQ' . date('Ymd',strtotime($field['recordDate'])),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => " and coid = '".self::$coid."'",
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'state' => '草稿',
                    'coid' => self::$coid,
                    'stid' => $this->control['stid'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
                //增加采购询价
                $purchaseInquiryId = self::getId();
                $purchaseInquiryuserNo = codeTemplateClass::generateCode('purchaseInquiry',[
                    'prefix' => 'CGXJ' . date('Ymd',strtotime($field['recordDate'])),
                    'table' => 'purchase_inquiry',
                    'field' => 'orderNo',
                    'where' => " and coid = '".self::$coid."'",
                ],$field);
                static::insert([
                    "table" => 'purchase_inquiry',
                    "field" => [
                        'id' => $purchaseInquiryId,
                        'coid' => self::$coid,
                        'orderNo' => $purchaseInquiryuserNo,
                        'purchaseNo' => $userNo,
                        'recordDate' => $field['recordDate'],
                        'sourceTable' => self::table,
                        'sourceId' => $id,
                        'text' => '',
                        'state' => '草稿',
                        'stid' => $this->control['stid'],
                    ],
                    "where" => "id = '$info[id]'",
                ]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
                $purchaseInquiryId = query('purchase_inquiry', "sourceId='".$id."'");
                $purchaseInquiryId = $purchaseInquiryId['id'];
            }

            //添加或更新报价单明细
            if (is_array($mxIdArr)) {
                foreach ($mxIdArr as $k => $nid) {
                    $mx = query(self::tableMx, "id = '$nid'");
                    $material = query('material', "id = '$materialIdArr[$k]'");
                    $numArr[$k] = self::formattingFigure($numArr[$k],'numPrecision');
                    if (!empty($mx['id'])) {
                        //更新
                        $warn = static::update([
                            "table" => self::tableMx,
                            "field" => [
                                'materialId' => $materialIdArr[$k],
                                'num' => $numArr[$k],
                                'unit'=>$unitArr[$k],
                                'price' => $material['buyPrice'],
                                'money' => self::formattingFigure($numArr[$k] * $material['buyPrice'] * (1 + $material['buyRate'])),
                                'rate' => $material['buyRate'],
                                'text' => $mxTextArr[$k],
                            ],
                            "where" => " id = '$nid'"
                        ]);
                        //增加采购询价详情
                        $purchaseInquiryDetail =  query('purchase_inquiry_detail', "orderId = '$purchaseInquiryId' and materialId='".$materialIdArr[$k]."'");
                        static::update([
                            "table" => 'purchase_inquiry_detail',
                            "field" => [
                                'materialId' => $materialIdArr[$k],
                                'num' => $numArr[$k],
                                'unit'=>$unitArr[$k],
                                'price' => $material['buyPrice'],
                                'money' => self::formattingFigure($numArr[$k] * $material['buyPrice'] * (1 + $material['buyRate'])),
                                'rate' => $material['buyRate'],
                                'text' => $mxTextArr[$k],
                            ],
                            "where" => " id = '".$purchaseInquiryDetail['id']."'"
                        ]);
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => self::tableMx,
                            "field" => [
                                'id' => $nid,
                                'orderId' => $id,
                                'coid' => self::$coid,
                                'materialId' => $materialIdArr[$k],
                                'unit'=>$unitArr[$k],
                                'num' => $numArr[$k],
                                'price' => $material['buyPrice'],
                                'money' => self::formattingFigure($numArr[$k] * $material['buyPrice'] * (1 + $material['buyRate'])),
                                'rate' => $material['buyRate'],
                                'text' => $mxTextArr[$k],
                            ],

                        ]);
                        //增加采购询价详情
                        static::insert([
                            "table" => 'purchase_inquiry_detail',
                            "field" => [
                                'id' => self::getId(),
                                'orderId' => $purchaseInquiryId,
                                'coid' => self::$coid,
                                'materialId' => $materialIdArr[$k],
                                'supplierId' => '',
                                'supplierName' => '',
                                'unit'=>$unitArr[$k],
                                'num' => $numArr[$k],
                                'price' => $material['buyPrice'],
                                'money' => self::formattingFigure($numArr[$k] * $material['buyPrice'] * (1 + $material['buyRate'])),
                                'history_min' => 0,
                                'is_select' => 0,
                                'rate' => $material['buyRate'],
                                'text' => $mxTextArr[$k],
                            ],

                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }
            //添加主表ID到附件表
            if (is_array($fileIdArr)) {
                $warn = update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
                if ($warn != '更新成功') {
                    $json['warn'] = $warn;
                    $isPass = false;
                }
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
                $this->commitTrans();
                delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"));
                if ($json['warn'] =='新增成功'){
                    auditClass::operateRecord($id,'采购申请','新建');
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
                $json['id'] = $id;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 保存并提交审批
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result = json_decode($resultJson,true);
        if ($result['warn'] == 2){
            $id = $result['id'];
            $body = self::encryptDecrypt(json_encode([
                'name'    => self::title,
                'table'   => self::table,
                'process' => [
                    // 预览函数
                    'detail' => [
                        'cla' => $this->get('cla'),
                        'fun' => 'detail',
                    ],
                    // 保存函数
                    'save'   => [
                        'cla' => $this->get('cla'),
                        'fun' => 'editEdit',
                    ],
                    //执行发起时验证函数
                    'before' => [
                        'cla' => $this->get('cla'),
                        'fun' => '',
                    ],
                    //完成发起后执行函数
                    'after'  => [
                        'cla' => $this->get('cla'),
                        'fun' => '',
                    ],
                ],
                'href' => isset($result['href'])?$result['href']:'',
            ], 320));
            $res = auditClass::submitApprovalSignle($id,$body);
            if($res['warn'] == 1){
                return $res['data']; //自定义审批人
            }elseif($res['warn'] != 2){
                $_SESSION['warn'] = '提交失败，'.$res['warn'];
            }
        }
        return $resultJson;
    }


    /**
     *
     * @return bool|string
     */
    public function addMx()
    {
        $materialClassObj = new materialClass();
        $layerId          = $this->get('cla') . ucwords($this->get('fun'));
        $formName         = 'mxForm';
        $notAllowRepeat   = 1;
        $data             = [
            'sub'            => " onclick=\"addRow();$('#" . $layerId . "').remove()\" ",
            'continueAdding' => $notAllowRepeat ? " onclick=\"addRow();removeSelectedContent('" . $formName . "')\" " : " onclick=\"addRow();\" ",
            'hidden'         => hidden(["name" => "notAllowRepeat", "value" => $notAllowRepeat]) .
                hidden(["name" => "supplyControl", "value" => '允许采购']) .
                hidden(array('name' => 'materialId', 'value' => $this->post('materialId') ? implode(',', $this->post('materialId')) : '')),
        ];
        return $materialClassObj->addMx($data);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit()
    {
        $mxIdArr = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = '请选择物料';
        } else {
            $tr = [];
            $title = self::title;
            $power = root . "control/adIndex.html?cla={$this->get('cla')}&fun=uploadIco";
            foreach ($mxIdArr as $mxId) {
                $material = query('material', "id = '$mxId'");
                $id = self::getId();
                $inventoryNum = machiningOrderClass::inventory($material['id'],$material['unit']);
                $unitSelect = select(array(
                    'name' => 'unit[]',
                    'data' => ['unit' => $material['unit']],
                    'change' => 'unitChange',
                    'option' => machiningOrderClass::unitOption($material['id']),
                    'title' => '单位',
                    'value' => $material['unit']
                ));
                $tr[]              = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $id)) .
                    hidden(array('name' => 'materialId[]', 'value' => $mxId)),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $unitSelect,
                    text(array('name' => 'num[]', 'blur' => 'calculateTotal', 'other' => self::digitalFiltering('numPrecision'), 'value' => '')),
                    "<span class='inventoryNum'>$inventoryNum</span>",
                    "<div class='clickIco' title='上传'><img  src='" . root . "img/control/clickEdit.svg?v=".version."' onClick=\"clickUpload('{$title}')\" class='edit-ico'>".
                    "<a target='_blank' id='{$id}Look' href=''><img alt='' src='" . root . "img/control/img.svg' title='' class='listIco'></a>".
                    "<a target='_blank' id='{$id}dow' href='' download='" . $material['name'] . "' title=''><img  alt='' src='" . root . "img/control/download.svg' class='listIco'></a></div>".
                    "<div class='hidden'><input name=\"singleFrameImgType\" type=\"hidden\"><input name=\"imageId[]\" id='{$id}' type=\"hidden\" value=''><input name='imgFile' accept=\"image/*\" id='imgFile' type='file' onchange=\"uploadImgFile(this,'{$power}','{$id}')\"></div>",
                    text(array('name' => 'mxText[]', 'class' => 'text textPrice')),
                ];
            }
            $json['html'] = $this->tableMany(array('tr' => $tr, 'thead' => false));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    /**
     * 审核按钮
     *
     * @param $info
     * @param $cancelFlag
     * @return array
     */
    public function auditButton($info,$cancelFlag): array
    {
        if (empty($info['id'])) {
            return [];
        }
        $button = [];
        if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'], 'selfChoose')) {
            $button[] = [
                "name"  => '提交审批',
                "type"  => "弹出层",
                "cla"   => 'audit',
                "fun"   => "operate",
                'style' => 'li-btn-blue-bg',
                "post"  => [
                    "act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'name'    => self::title,
                        'table'   => self::table,
                        'process' => [
                            // 预览函数
                            'detail' => [
                                'cla' => $this->get('cla'),
                                'fun' => 'detail',
                            ],
                            // 保存函数
                            'save'   => [
                                'cla' => $this->get('cla'),
                                'fun' => 'editEdit',
                            ],
                            //执行发起时验证函数
                            'before' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                            //完成发起后执行函数
                            'after'  => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                        ],
                    ], 320)),
                ],
            ];
        }
        // 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name"  => '审批',
                "type"  => "弹出层",
                "cla"   => 'audit',
                "fun"   => "operate",
                // 以下参数固定格式
                "post"  => [
                    "act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table'   => self::table,
                        // 当前状态
                        'state'   => $info['state'],
                        // 变更
                        'field'   => ['state'],   //变更字段 可多个
                        'value'   => [
                            'state' => ['草稿', '已通过'],
                        ],
                        // 审核时回调
                        'process' => [
                            //执行首次审核时验证
                            'before' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                            //执行末次审核后处理
                            'after'  => [
                                'cla'  => $this->get('cla'),
                                'fun'  => '',
                            ],
                        ],
                    ], 320)),
                ],
                'style' => 'li-btn-blue-bg',
            ];
            $button[] = [
                "name" => '添加审批人',
                "type" => "弹出层",
                "cla"  => 'audit',
                "fun"  => "operate",
                "post" => [
                    "act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                    ], 320)),
                ],
            ];
            $button[] = [
                "name" => '转交',
                "type" => "弹出层",
                "cla"  => 'audit',
                "fun"  => "operate",
                "post" => [
                    "act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                    ], 320)),
                ],
            ];
        }
        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿' && $cancelFlag) {
            $button[] = [
                "name" => '撤销审批',
                "type" => "弹出层",
                "cla"  => 'audit',
                "fun"  => "operate",
                "post" => [
                    "act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table'   => self::table,
                        // 当前状态
                        'state'   => $info['state'],
                        // 变更
                        'field'   => ['state'],   //变更字段 可多个
                        'value'   => [
                            'state' => ['草稿'],
                        ],
                        'process' => [
                            //完成发起后执行函数
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                        ],
                    ], 320)),
                ],
            ];
        }
        return $button;
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );

            $button = [];
            if ($info['state'] == '草稿') {
                if ($this->power(self::page, "del")) {
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
                if ($this->power(self::page, "edit")) {
                    $button[] = [
                        "name" => "编辑",
                        "type" => "顶部页卡",
                        "title" => self::title,
                        "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                    ];
                }
            }
            //审核按钮
            $cancelFlag = static::total(array(
                'table' => 'purchase_order_detail',
                'where' => "sourceId in (select id from " . self::tableMx . " where orderId = '".$info['id']."') and coid = '" . self::$coid . "'"
            )) > 0 ? false : true;
            $button = array_merge($button, $this->auditButton($info, $cancelFlag));
            if ($this->power(self::page, "close") && $info['state'] == '已通过') {
                //按钮
                $isClose = $info['isClose'] == 1 ? 0 : 1;
                $name = $info['isClose'] == 1 ? '开启' : '关闭';
                $button[] = [
                    "name" => $name,
                    "type" => "点击事件",
                    "fun" => "layer('" . self::page . "','stateSwitch',{id:'" . $info['id'] . "',type:'{$isClose}'})",
                ];
            }
            $button[] = [
                "name" => "单据追踪",
                "type" => "顶部页卡",
                "title" => "单据追踪",
                "url" => $this->root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=采购申请单&id=" . $info['id'],

            ];

            $tr[] = ['物料编码', '物料名称', '规格型号', '单位', '数量', '可用库存', '备注'];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by list"));
            $totalArr = ['num'=>0,'inventory'=>0];
            foreach ($result['array'] as $array) {
                $material = query('material', " id = '$array[materialId]'");
                $inventoryNum = machiningOrderClass::inventory($material['id'],$material['unit']);
                $tr[] = [
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    self::lostZero($array['num'],'numPrecision'),
                    $inventoryNum,
                    $array['text'],
                ];
                $totalArr['num'] += $array['num'];
                $totalArr['inventory'] += $inventoryNum;
            }
            $total_tr = [
                    4=>$totalArr['num']?self::lostZero($totalArr['num'],'numPrecision'): 0,
                    5=>$totalArr['inventory']?self::lostZero($totalArr['inventory'],'numPrecision'): 0,
            ];
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                array(
                    array(
                        "请购类型" => $info['type'],
                        "单据日期" => self::null($info['recordDate']),
                        "需求日期" => self::null($info['demandDate']),
                    ),
                    array(

                        "备注" => pre($info['text']),
                        "类型" => $info['goods_type'],
                    ),
                    array(
                        "单据编号" => $info['orderNo'],
                        "制单人" => self::findStaff($info['stid']),
                        "状态" => $info['state']. self::operateRecord($info['id']),
                    ),
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '请购明细',
                'html' => $this->listTable(array('tr' => $tr, 'showEmpty' => true, 'total' => $total_tr, 'showSort' => true)),
            ]);
            $data['html'] .= $this->detailBlock([
                '附件' => fileUploadClass::showFile($info['id'], self::title),
                '流程' => auditClass::auditRecord(self::table, $info['id'])
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '已确认',
            'checkId' => self::$stid,
            'confirmTime' => $this->time
        ];
        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此采购申请单';
        } elseif ($info['state'] != '待确认') {
            $json['warn'] = '此采购申请单不是待确认状态，不能确认';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditClass::operateRecord($id,'采购申请单','确认');
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 撤回
     */
    public function cancelEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '草稿',
            'checkId' => '',
            'confirmTime' => ''
        ];
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '你还没有撤回权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此采购申请单';
        } elseif ($info['state'] != '已确认') {
            $json['warn'] = '此报价单不是已确认状态，无需撤回';
        } elseif (static::total(array(
            'table' => 'purchase_order_detail',
            'where' => "sourceId in (select id from " . self::tableMx . " where orderId = '$id') and coid = '" . self::$coid . "'"
            )) > 0) {
            $json['warn'] = '此申请单已在采购单中使用，暂不能撤回';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditClass::operateRecord($id,'采购申请单','撤回');
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 提交
     */
    public function commitEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待确认',
        ];
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此采购申请单';
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = '此报价单不是草稿状态，不能提交';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditClass::operateRecord($id,'采购申请单','提交');
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 操作记录
     */
    public static function operateRecord($id): string
    {
        $result = find(['table' => 'auditing_follow', 'where' => "typeId = '$id' order by time desc"]);
        $li     = '';
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                $li .= "<li>{$array['text']}&emsp;{$array['time']}</li>";
            }
        }
        if (empty($li)) {
            $li = "<li>暂无记录</li>";
        }
        return "&emsp;<span class='del-row-button' id='record'>操作记录<div class='stateBlock operate-content'><ul>$li</ul></div></span>";
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = $word = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否已确认此采购申请单，确认后将不可修改？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认提交此采购申请单？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认撤回此采购申请单？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'close':
                $act = 'close';
                $msg = '关闭';
                $title = '是否确认批量关闭采购申请？';
                $function = 'closeEdit';
                $form = self::page . 'OperateForm, listForm, quoForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm, quoForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 启用/停用
     */
    public function stateSwitch(): bool|string
    {
        $isClose = $this->post('type');
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否确认" . ($isClose == 1 ? '关闭' : '开启') . "此申请？",
            ),
        ), 'hidden' => hidden(array('name' => 'type', 'value' => $isClose)), 'formTwo' => 'listForm'));
        //返回
        return $this->layer(array("title" => "采购申请状态", "height" => 165, "html" => $html));
    }

    /**
     * 启用/停用
     */
    public function stateSwitchEdit(): bool|string
    {
        $idArr = $this->post('id') ? [$this->post('id')] : $this->post('listId');
        $isClose = $this->post('type');
        if (!$this->power(self::page, "close")) {
            $json['warn'] = "你没有" . self::title . "的编辑权限";
        } elseif (empty($idArr) || !is_array($idArr)) {
            $json['warn'] = "请选择数据";
        } else {
            $field = [
                'isClose' => $isClose,
            ];
            $json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " id in ('" . implode("','", $idArr) . "')"));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $type = $isClose == 1 ? '关闭' : '开启';
                foreach ($idArr as $id) {
                    auditingFollow(array(
                        "type" => "采购申请",
                        "typeId" => $id,
                        "text" => "【{$this->control['name']}】" . $type,
                    ));
                }
                //添加日志
                $text = $this->control['name'] . $type . "了" . self::title . "， id：【" . implode(",", $idArr) . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $type . '成功';
                $json['warn'] = 2;
            }
        }
        //返回
        return json_encode($json, 320);
    }

    /**
     * 批量关闭采购申请
     *
     * @return bool|string
     */
    public function closeEdit()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有操作的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ", "isClose");
                if ($info['isClose'] == 1) {
                    $warn = "操作失败：已关闭，请勿重复操作";
                } else {
                    update(array('table' => self::table, 'field' => ['isClose' => 1], 'where' => " id = '$id' "));
                    auditingFollow(array(
                        "type" => "采购申请",
                        "typeId" => $id,
                        "text" => "【{$this->control['name']}】关闭",
                    ));
                    //返回
                    $warn = "关闭成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $id . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "关闭了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "关闭了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = "删除失败：已确认，暂不能删除";
                } else {
                    //最后删除基本参数
                    fileClass::deleteFile($id);
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    delete(array("table" => 'auditing_follow', "where" => " typeId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

}

